package com.aabte.server;

import com.aabte.server.config.bean.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Pattern;
import java.util.Objects;

@RestController
@Api(value = "/", description = "这是我全部的post请求")
@RequestMapping("/v1")
public class MyPostMethod {

    // 这个变量是用来保存Cookies信息
    private static Cookie cookie;

    @PostMapping("/login")
    @ApiOperation(value = "登陆接口，成功后获取Cookies信息", httpMethod = "POST")
    public String login(
            @Pattern(regexp = "^[a-zA-Z_][a-zA-Z_0-9]{5,15}", message = "用户名格式不正确！")
            @ApiParam(value = "用户名")
            @RequestParam String username,

            @RequestParam @ApiParam(value = "密码") String password,
            HttpServletResponse response) {
        if ("huhansan".equals(username) && "123456".equals(password)) {
            Cookie cookie = new Cookie("login", "true");
            response.addCookie(cookie);
            return "登陆成功！";
        } else {
            return "登陆失败！";
        }
    }

    @PostMapping("/getUserList")
    @ApiOperation(value = "获取用户列表", httpMethod = "POST")
    public User getUserList(
            @RequestBody User user,
            HttpServletRequest request,
            HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        User user1 = new User();
        if (!Objects.isNull(cookies)) {
            for (Cookie cookie :cookies) {
                if ("login".equals(cookie.getName())
                        && "true".equals(cookie.getValue())
                        && "zhangsan".equals(user.getUsername())
                        && "123456".equals(user.getPassword())) {
                    user1.setUsername("li001");
                    user1.setName("lisi");
                    user1.setAge("16");
                    user1.setSex("man");
                    return user1;
                }
            }
        }
        return user1;
    }

}
